package com.answer.controller;
import cn.hutool.core.io.FileUtil;
import com.answer.constant.FileConstant;
import com.answer.excepction.BaseException;
import com.answer.model.entity.User;
import com.answer.model.enums.FileUploadBizEnum;
import com.answer.model.reslut.Result;
import com.answer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {


    @Resource
    private UserService userService;

    // @Resource
    // private CosManager cosManager;

    /**
     * 文件上传
     *
     * @param
     * @param
     * @param
     * @return
     */
    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                     String type, HttpSession httpSession) {
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(type);
        if (fileUploadBizEnum == null) {
            throw new BaseException("");
        }
        validFile(multipartFile, fileUploadBizEnum);
        User user = ( User) httpSession.getAttribute("user");
        //文件目录：根据业务、用户来划分
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s", fileUploadBizEnum.getValue());
        File file = null;
        try {
            //上传文件
            file = new File("D://"+filepath,filename);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            multipartFile.transferTo(file);
            // cosManager.putObject(filepath, file);
            // 返回可访问地址
            return Result.success(FileConstant.FILE_HOST +filename);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BaseException("");
        }
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BaseException( "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BaseException("文件类型错误");
            }
        }
    }
}